<template>
  <div class="chart-container">
    <div class="filter-container">
        <el-select 
          v-model="selectedCountry" 
          placeholder="Select a country" 
          @change="handleFilterChange"
          style="width: 200px; margin-right: 20px;margin-bottom: 20px;"
          size='large'
        >
          <el-option label="All countries" value="all" />
          <el-option 
            v-for="country in countryOptions" 
            :key="country" 
            :label="country || 'Unknown country'" 
            :value="country || 'unknown'"
          />
        </el-select>
        
        <el-select 
          v-model="selectedAge" 
          placeholder="Select age group" 
          @change="handleFilterChange"
          style="width: 200px;"
          size='large'
        >
          <el-option label="All age groups" value="all" />
          <el-option 
            v-for="age in ageOptions" 
            :key="age" 
            :label="age || 'Unknown age group'" 
            :value="age || 'unknown'"
          />
        </el-select>
      </div>
    <div class="scroll-container">
      <div class="chart-wrapper">
        <el-empty v-if="!filteredData.length" style="height: 500px;"/>
        <div v-else ref="chartRef" style="height: 500px;"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, nextTick, onBeforeUnmount, computed,watch } from 'vue'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  import * as echarts from 'echarts'
  import { useLoading } from '../../utils/loading';
  import { useSidebarStore } from '../../store/sidebarStore';

  const BASE_URL = import.meta.env.VITE_API_URL
  const sidebarStore = useSidebarStore();
  const isCollapse = computed(() => sidebarStore.isCollapse);
  const { showLoading, hideLoading } = useLoading();
  // 数据相关
  const rawData = ref([])
  const chartRef = ref(null)
  let chartInstance = null
  // 筛选相关
  const selectedCountry = ref('all')
  const selectedAge = ref('all')
  watch(isCollapse,async(newVal) => {
    await getAgeData();
  },{ flush: 'post' }) 
  
  const countryOptions = computed(() => {
    const countries = new Set()
    rawData.value.forEach(item => {
      countries.add(item.country)
    })
    return Array.from(countries).sort()
  })
  const ageOptions = computed(() => {
    const ages = new Set()
    rawData.value.forEach(item => {
      ages.add(item.title)
    })
    return Array.from(ages).sort((a, b) => {
      // 对年龄段进行排序
      const getOrder = (age) => {
        if (!age) return 0
        if (age.includes('16')) return 1
        if (age.includes('31')) return 2
        if (age.includes('41')) return 3
        if (age.includes('50+')) return 4
        return 5
      }
      return getOrder(a) - getOrder(b)
    })
  })

  // 处理筛选后的数据
  const filteredData = computed(() => {
    if (!rawData.value.length) return []
    
    let data = [...rawData.value]
    
    // 国家筛选
    if (selectedCountry.value !== 'all') {
      const countryFilter = selectedCountry.value === 'unknown' ? null : selectedCountry.value
      data = data.filter(item => 
        (item.country === countryFilter) || 
        (selectedCountry.value === 'unknown' && item.country === null))
    }
    
    // 年龄段筛选
    if (selectedAge.value !== 'all') {
      const ageFilter = selectedAge.value === 'unknown' ? '' : selectedAge.value
      data = data.filter(item => 
        (item.title === ageFilter) || 
        (selectedAge.value === 'unknown' && item.title === ''))
    }
    
    return data
  })

  // 获取数据
  const getAgeData = async() => {
    showLoading('loading...')
    try {
      const res = await axios.get(`${BASE_URL}manage/countAgeRange`, {
        params: { country: null }
      })
      
      if (res.data?.data) {
        rawData.value = res.data.data
        nextTick(() => {
          renderChart()
        })
      }
    } catch(error) {
      ElMessage.error('Failed to obtain data')
    } finally {
      hideLoading();
    }
  }

  // 渲染图表
  const renderChart = () => {
    if (!filteredData.value.length) {
      if (chartInstance) {
        chartInstance.dispose()
        chartInstance = null
      }
      return
    }
    
    // 销毁旧实例
    if (chartInstance) {
      chartInstance.dispose()
      chartInstance = null
    }
    
    try {
      // 初始化图表
      chartInstance = echarts.init(chartRef.value)
      
      // 根据当前筛选条件决定显示什么图表
      let option
      if (selectedAge.value !== 'all') {
        // 显示国家占比
        option = getCountryOption()
      } else if (selectedCountry.value !== 'all') {
        // 显示年龄占比
        option = getAgeOption()
      } else {
        // 显示全部数据的国家分布
        option = getAllCountriesOption()
      }
      
      chartInstance.setOption(option)
      
      // 窗口大小变化时重绘图表
      window.addEventListener('resize', resizeHandler)
      
    } catch (error) {
    }
  }

  // 获取国家占比图表配置
  const getCountryOption = () => {
    const countryMap = {}
    
    filteredData.value.forEach(item => {
      const country = item.country !== null ? item.country : 'Unknown country'
      countryMap[country] = (countryMap[country] || 0) + item.total
    })
    
    const data = Object.entries(countryMap).map(([name, value]) => ({
      name,
      value
    }))
    
    return {
      title: {
        text: `Age group ${selectedAge.value === 'unknown' ? 'unknown' : selectedAge.value} National distribution`,
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}person ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        data: data.map(item => item.name)
      },
      series: [
        {
          name: 'Country distribution',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data
        }
      ]
    }
  }

  // 获取年龄占比图表配置
  const getAgeOption = () => {
    const ageMap = {}
    
    filteredData.value.forEach(item => {
      const age = item.title !== '' ? item.title : 'Unknown age group'
      ageMap[age] = (ageMap[age] || 0) + item.total
    })
    
    const data = Object.entries(ageMap).map(([name, value]) => ({
      name,
      value
    }))
    
    // 按年龄段排序
    data.sort((a, b) => {
      const order = ['16~30', '31~40', '41~50', '50+', 'Unknown age group']
      return order.indexOf(a.name) - order.indexOf(b.name)
    })
    
    return {
      title: {
        text: `Country ${selectedCountry.value === 'unknown' ? 'unknown' : selectedCountry.value} Age distribution`,
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}person ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 20,
        bottom: 20,
        data: data.map(item => item.name)
      },
      series: [
        {
          name: 'Age distribution',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data
        }
      ]
    }
  }

  // 获取全部国家图表配置
  const getAllCountriesOption = () => {
    const countryMap = {}
    
    filteredData.value.forEach(item => {
      const country = item.country !== null ? item.country : 'Unknown country'
      countryMap[country] = (countryMap[country] || 0) + item.total
    })
    
    const data = Object.entries(countryMap).map(([name, value]) => ({
      name,
      value
    }))
    
    return {
      title: {
        text: 'User distribution in various countries',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}person ({d}%)'
      },
      legend: {
        orient: 'vertical',
        top: '10%',
        left: 'left',
        data: data.map(item => item.name)
      },
      series: [
        {
          name: 'Country distribution',
          type: 'pie',
          center: ['60%', '55%'],
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data
        }
      ]
    }
  }

  // 筛选条件变化时重绘图表
  const handleFilterChange = () => {
    nextTick(() => {
      renderChart()
    })
  }

  // 调整图表大小
  const resizeHandler = () => {
    if (chartInstance) {
      try {
        chartInstance.resize()
      } catch (e) {
      }
    }
  }

  onMounted(() => {
    getAgeData()
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHandler)
    if (chartInstance) {
      try {
        chartInstance.dispose()
      } catch (e) {
      }
    } 
  })
</script>

<style scoped>
  .chart-wrapper {
    width: 100%;
  }

  .filter-container {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }

  /* 新增滚动容器样式 */
  .scroll-container {
    width: 100%;
    overflow-x: auto;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 20px;
    box-sizing: border-box;
  }

  .chart-container {
    height: 500px;
  }
  .custom-height .el-input__inner {
  height: 80px !important;       /* 自定义高度 */
  line-height: 80px !important;  /* 确保文字垂直居中 */
  padding: 0 15px;    /* 调整内边距 */
}
</style>